from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
import time
import requests
import re
import json
import configparser
import pathlib
import base64


class run(object):
    def __init__(self, username, password):
        self.usn = username
        self.pwd = password

    def requests(self):
        def getuserip():
            html = requests.get('https://www.baidu.com', verify=False)
            userip = re.findall(r'wlanuserip=(.*?)&wlan', html.text)[0]
            return userip

        userip = getuserip()
        headers = {
            'Host': '172.16.2.100',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.91 Mobile Safari/537.36',
            'Referer': 'http://172.16.2.100/eportal/index.jsp?wlanuserip=' + userip + '&wlanacname=6a4176e06680c5ae8030c5e5d8225f73&ssid=&nasip=518f32fe1f6799fd406a10390c7639d5&snmpagentip=&mac=5ecc6f297d580649fcf8676324d469d7&t=wireless-v2&url=f096fb179a85a017da7bcd02fa355b6f2203c39847362bc0&apmac=&nasid=6a4176e06680c5ae8030c5e5d8225f73&vid=43b03da3704d3b14&port=c76d2eb5e2ff5438&nasportid=b1e49c6541daf461a9825ea14f44b8cbfee6b337d83e6f141df6f84229cbab3d64ddb41213854563',
            'Connection': 'keep-alive',
            'Accept-Language': 'zh-CN,zh;q=0.9',
        }
        data = {
            'userId': self.usn,
            'password': self.pwd,
            'service': '',
            'queryString': 'wlanuserip%3D' + userip + '%26wlanacname%3D6a4176e06680c5ae8030c5e5d8225f73%26ssid%3D%26nasip%3D518f32fe1f6799fd406a10390c7639d5%26snmpagentip%3D%26mac%3D5ecc6f297d580649fcf8676324d469d7%26t%3Dwireless-v2%26url%3Df096fb179a85a017da7bcd02fa355b6f2203c39847362bc0%26apmac%3D%26nasid%3D6a4176e06680c5ae8030c5e5d8225f73%26vid%3D43b03da3704d3b14%26port%3Dc76d2eb5e2ff5438%26nasportid%3Db1e49c6541daf461a9825ea14f44b8cbfee6b337d83e6f141df6f84229cbab3d64ddb41213854563',
            'operatorPwd': '',
            'operatorUserId': '',
            'validcode': '',
            'passwordEncrypt': 'false',
        }
        url = 'http://172.16.2.100/eportal/InterFace.do?method=login'
        response = requests.post(url=url, data=data, headers=headers)
        result = response.json()
        result_1 = json.dumps(response.json(),ensure_ascii=False)
        result1 = result_1.encode('ISO-8859-1')
        result1 = result1.decode('utf-8')
        if '"message": "密码不匹配，请输入正确的密码!"' in result1:
            return '账户错误'
        elif '"message": "你使用的账号已达到同时在线用户数量上限!"' in result1:
            return '你使用的账号已达到同时在线用户数量上限!'
        else:
            userIndex = str(result['userIndex'])
            requests.post('http://172.16.2.100/eportal/InterFace.do?method=getOnlineUserInfo',
                          data={'userIndex': userIndex}, headers=headers)
            time.sleep(1)
            response = requests.post('http://172.16.2.100/eportal/InterFace.do?method=getOnlineUserInfo',
                                     data={'userIndex': userIndex}, headers=headers)
            response.encoding = 'utf-8'
            user = response.text
            user = json.loads(user)
            tips = user['welcomeTip']  # 获取tip
            userName = user['userName']  # 用户名称
            # userPackage = user['userPackage']#获取用户套餐
            userGroup = user['userGroup']  # 获取用户组别
            # userPhone = user['userId']#获取用户电话
            data_1 = {
                'userGroup': userGroup,
                'userName': userName,
                'tips': tips,
                'userip': userip,
                'userIndex': userIndex[-12:-1]
            }
            # t = time.ctime()
            if verify('https://www.baidu.com'):
                return '成功'
            else:
                return '失败'


def verify(url):  # 验证
    try:
        r = requests.get(url)
        return True
    except:
        return False


class account(object):
    def __init__(self, username, password):
        self.usn = username
        self.pwd = password

    def setini(self):  # 设置ini
        conf = configparser.ConfigParser()
        path = pathlib.Path('account.ini')
        if path.exists():
            return '已存在用户信息'
        else:
            username = str(base64.b64encode(self.usn.encode('utf-8')), 'utf-8')
            password = str(base64.b64encode(self.pwd.encode('utf-8')), 'utf-8')
            conf['user'] = {
                'username': username,
                'password': password
            }
            with open('account.ini', 'w') as file:
                conf.write(file)
                file.close()
            return '用户信息已保存'

    def cleanini(self):  # 清除ini
        path = pathlib.Path('account.ini')
        path.unlink()

    def obtainini(self):
        conf = configparser.ConfigParser()
        path = pathlib.Path('account.ini')
        if path.exists():
            conf.read('account.ini')
            username_en = conf['user']['username']
            password_en = conf['user']['password']
            username_de = str(base64.b64decode(username_en))
            password_de = str(base64.b64decode(password_en))
            account = [username_de[2:-1],password_de[2:-1]]
            return account
        else:
            return '配置信息不存在'


def reconnection():
    url1 = 'https://www.baidu.com'
    url2 = 'http://172.16.2.100'
    account1 = account.obtainini()
    while (True):
        if not verify(url1):  # 判断是否联网
            if verify(url2):  # 判断是否在校园网范围内
                run(username=account1[0], password=account1[1])
        time.sleep(5)
